package com.example.app14_network;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";

    private File apkFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        Log.i(TAG, "onCreate()");

        // 初始化视图控件
        Button btnMainDownload = findViewById(R.id.btn_main_download);

        // 给按钮添加点击事件
        btnMainDownload.setOnClickListener(this);
    }

    /**
     * 处理按钮点击事件
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        // 主线程显示进度条
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.show();
        // 准备用于保存apk文件的File对象
        apkFile = new File(getExternalFilesDir(null), "update.apk");
        // 启动分线程，请求下载apk文件
        new Thread(() -> {

            String path = "http://10.189.124.52:8080/apk/app12_data_storage-debug.apk";

            try {
                // 获取连接对象
                URL url = new URL(path);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                // 设置超时时间
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(10000);
                // 连接
                connection.connect();
                if (connection.getResponseCode() == 200) {
                    // 设置进度条的最大值
                    dialog.setMax(connection.getContentLength());

                    // 获取apk文件的InputStream
                    InputStream in = connection.getInputStream();
                    // 获取指向apkFile的OutputStream
                    OutputStream out = new FileOutputStream(apkFile);
                    byte[] buf = new byte[1024];
                    int len;
                    while((len = in.read(buf)) != -1) {
                        out.write(buf, 0, len);
                        // 显示下载进度
                        dialog.incrementProgressBy(len);
                        // 模拟网络
                        // Thread.sleep(50);
                        SystemClock.sleep(50);
                    }

                    out.close();
                    in.close();
                }

                // 下载完成，关闭连接
                connection.disconnect();

                // 主线程移除dialog，执行安装
                runOnUiThread(() -> {
                    dialog.dismiss();
                    installApk();
                });

            } catch (IOException e) {
                dialog.dismiss();
                Log.e(TAG, "onClick: " + e.getMessage(), e);
                Thread.currentThread().interrupt();
            }

        }).start();
    }

    /**
     * 启动安装apk
     */
    private void installApk() {
        Intent installIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        installIntent.setDataAndType(Uri.fromFile(apkFile),
                "application/vnd.android.package-archive");
        startActivity(installIntent);
    }
}